package org.ushio.nchu_22201408.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.ushio.common_module.entity.User;
import org.ushio.common_module.entity.UserBanTime;
import org.ushio.nchu_22201408.Feign.Admin_UserClient;
import org.ushio.nchu_22201408.mapper.UserMapper;
import org.ushio.nchu_22201408.service.UserService;
import org.ushio.nchu_22201408.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.ushio.nchu_22201408.util.TokenResponse;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;
    private final JwtUtil jwtUtil;
    private final UserMapper userMapper;

    @Autowired
    private Admin_UserClient adminUserClient;

    @Autowired
    public UserController(UserService userService, JwtUtil jwtUtil, UserMapper userMapper) {
        this.userService = userService;
        this.userMapper = userMapper;
        this.jwtUtil = jwtUtil;
    }

    @GetMapping("/{phoneNumber}")
    public User getUserByPhoneNumber(@PathVariable String phoneNumber) {
        return userService.findUserByPhoneNumber(phoneNumber);
    }

    @GetMapping("/find/{phoneNumber}")
    public User getUserByPhoneNumber2(@PathVariable String phoneNumber) {
        if(userService.judgeFindUserByPhoneNumber(phoneNumber)) {
            return userService.findUserByPhoneNumber(phoneNumber);
        }else{
            return null;
        }
    }

    @PostMapping("/register")
    public String registerUser(@RequestBody User user) {
        boolean isRegistered = userService.registerUser(user);
        if (isRegistered) {
            return "User registered successfully!";
        } else {
            return "Registration failed!";
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody User user) {
        boolean isLoggedIn = userService.loginUser(user.getPhoneNumber(), user.getPassword());
        if (isLoggedIn) {
            String token = userService.generateToken(user.getPhoneNumber(), user.getPassword());
            return ResponseEntity.ok(new TokenResponse(token));
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Login failed!");
        }
    }

    @GetMapping("/info")
    public ResponseEntity<?> getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("Authorization"); // 移除了final关键字
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                String phoneNumber = jwtUtil.extractUsername(token);
                User user = userService.findUserByPhoneNumber(phoneNumber);
                if (user != null) {
                    return ResponseEntity.ok(user);
                } else {
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
                }
            } catch (Exception e) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token");
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authorization header must be provided");
        }
    }

    @PostMapping("/update")
    public ResponseEntity<?> updateUser(@RequestBody User user, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                String phoneNumber = jwtUtil.extractUsername(token);
                if (phoneNumber.equals(user.getPhoneNumber())) {
                    User existingUser = userService.findUserByPhoneNumber(phoneNumber);
                    if (existingUser != null) {
                        existingUser.setUserName(user.getUserName());
                        existingUser.setGender(user.getGender());
                        existingUser.setPassword(user.getPassword());
                        existingUser.setIdCardNumber(user.getIdCardNumber());
                        existingUser.setAddress(user.getAddress());
                        // 更新用户信息
                        userMapper.updateUser(existingUser);
                        return ResponseEntity.ok("User info updated successfully");
                    } else {
                        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
                    }
                } else {
                    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");
                }
            } catch (Exception e) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token");
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authorization header must be provided");
        }
    }

    @GetMapping("/all")
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return ResponseEntity.ok(users);
    }
    @PostMapping("/ban")
    public ResponseEntity<?> banUser( @RequestBody User user) {
        boolean isBanned = userService.banUser(user.getPhoneNumber());
        if (isBanned) {
            return ResponseEntity.ok("User banned successfully");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("User is already banned or does not exist");
        }
    }

    @GetMapping(value = "/getBanIfo")
    public List<UserBanTime> getUserBanTimes(@RequestParam(value = "Phone_Number")String Phone_Number) {
        return adminUserClient.getUserBanIfo(Phone_Number);
    }

}